package com.wzl.policy.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间日期工具类
 *
 * @author weizhongli
 * @since 2022-08-22 17:39
 */
@Slf4j
@Component
public class DateUtil {

    public static final String TIME_PATTERN = "yyyyMMddHHmmss";

    public static String format(Date date, String pattern) {
        return date == null ? "" : new SimpleDateFormat(pattern).format(date);
    }

    public static Date getDateObj(String dateStr, String format) {
        try {
            SimpleDateFormat formatObj = new SimpleDateFormat(format);
            return formatObj.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取当前时间戳
     * @return
     */
    public static String getCurrentTimeFullData() {
        return format(new Date(), TIME_PATTERN);
    }


    public static String format(Calendar cal, String pattern) {
        return cal == null ? "" : new SimpleDateFormat(pattern).format(cal.getTime());
    }

    /**
     * 获取24小时前时间戳
     * @return
     */
    public static String getPreDay(String date, String format){
        Date dateObj = getDateObj(date, format);
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateObj);
        cal.set(Calendar.DAY_OF_MONTH, (cal.get(Calendar.DAY_OF_MONTH) - 1));
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(cal.getTime());
    }

}